//
//  ViewController.swift
//  SwiftStudy
//
//  Created by apple on 16/12/24.
//  Copyright © 2016年 com.zaoguankeji.www. All rights reserved.
//

import UIKit
import Darwin
class ViewController: UIViewController {
 let people = ["David", "Chris", "Joe", "Jordan", "Tony", "Tom"]
    
    @IBOutlet var shagkeImage: FoodImageView!
    
    @IBOutlet weak var enterBtn: ActionButton!
    
    @IBAction func shakeBtn(_ sender: Any) {
        
        enterBtn.shake()
        shagkeImage.shake()
        DispatchQueue.main.asyncAfter(deadline: 2, execute:{
            
            ///创建StoryBoard的方法
            let storyboard = UIStoryboard(.news)
            let viewController: ArticleViewController = storyboard.instantiateViewController()
            self.navigationController?.pushViewController(viewController, animated: true)
        })
    }
    

    @IBOutlet var selectBtn: [UIButton]! {
    ///首先，需要确认这些表情按钮默认是被隐藏的。遍历所有的表情按钮，使之隐藏。
        didSet{
            var  i = 0
            
            selectBtn.forEach {
                $0.isHidden = true
                $0.tag = selectBtn.index(of: $0)!
                i = i + 1
                $0.addTarget(self, action: #selector(touchBtn(_:)), for: .touchUpInside)
            }
        }
    }
    
   @objc func touchBtn(_ sender:UIButton) {
    switch sender.tag {
    case 0:
        print(sender.tag)
    case 1:
        print(sender.tag)
    case 2:
        print(sender.tag)
    case 3:
        print(sender.tag)
    case 4:
        print(sender.tag)
    case 5:
        print(sender.tag)
    default:
        break
    }
    
//    print(sender.tag)
    
    }
    var stringDate: String!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let data = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm:ss E M dd zzz GGG"
        stringDate = data.fullString
//        print(stringDate) // 14:20:31 Fri 8 19 GMT+8 AD
        

       
        print()
        ///时间
//        let comp = DateComponents(calendar: nil, timeZone: nil, era: nil, year: 2016, month: 12, day: 26, hour: 12, minute: 14, second: 45, nanosecond: nil, weekday: nil, weekdayOrdinal: nil, quarter: nil, weekOfMonth: nil, weekOfYear: nil, yearForWeekOfYear: nil)
     
        let  date = Date()
        let timeFormatter = DateFormatter()
        timeFormatter.dateFormat = "yyy-MM-dd 'at' HH:mm:ss.SSS" ///(格式可俺按自己需求修整)
        var strNowTime = timeFormatter.string(from: date) as String
        
        let  todayCom = date.yesterday.dateAndTimeComponents
//        DateComponents
        
        print(date.yesterday.iso8601String)

         let  c = date - 100000
         let docment1 = DateComponents(second: 90)
        
        
        print(docment1.description(units: .full, remaining: false, approximate: false, style: .approximate))
        print(date.iso8601String)
//      let afterdate =  date.dispatchTime(after: 30)
//        print(afterdate)
        let random1 = random(from: 1..<20)
        print(random1)
        let random2 = random(from:CountableRange( 1...20))
        print(random2)
       
        let winner = people.random()
        print(winner as Any)
       let a  = (1...9).random()
        print(a!)
        DispatchQueue.main.asyncAfter(deadline: 5, execute:{
                print("6666")
                
        }
        )
        ///异常处理
        do {
            let imageData = Data()
            _ = try UIImage(data: imageData).unwrap()
        } catch { print(error) }
        
        /*我试图通过下面几步，通过最少的数据复制，高效地创建一个字节数组
         创建一个空的字节数组。
         在数组中预留充足的空间。
         使用可变指针去做数组的数据填充。
         只有数组被填充之后，才能知道它的实际大小。
         我想要设置数组的大小为它被填充的实际大小。
          */
        createFullName("44", lastname: "33")
        ///创建一个序列（Sequence）来表示你想要填充的数据
        var b  = [0]
        b.reserveCapacity(200)
        b += sequence(first: 3, next: {$0 < 1000 ? ($0 + 3) * 2 : nil})
        for i in 1..<2000 {
        b.append(i)
        
        }
        print(b.count)
        print(DispatchTime.now().rawValue)
        
        
        /// 声明常量后，在一个紧接着的闭包中进行初始化，
        ///定义一个常量
        let yellowView: UIView = {
        
            $0.backgroundColor = .yellow
            $0.frame = view.bounds
            return $0
            
        }(UIView())
        ///then
        let label = UILabel().then {
            $0.frame = CGRect(x: 40, y: 40, width: 100, height: 44)
            $0.textAlignment = .center
            $0.textColor = .black
            $0.text = "Hello, World!"
        }
//        view.addSubview(yellowView)
        view.addSubview(label)
        
        
//        let today = Date()
//        print("WWWWWW  \(today)")
        let docment = DateComponents(minute: 15)
        
//          print(docment.members)
        ///XibLoading
//        print((Date() + DateComponents.days(-3) + DateComponents.hours(1)).fullString)
//           print(today.components.description(units: .full, remaining: false, approximate: false, style: .approximate))
        
        DispatchQueue.main.asyncAfter(deadline: 50, execute:{
        
            
        })
       
        
//         print(Date().offset(.day, 1).fullString)
        let myview = MyView.getView()
            view.addSubview(myview)
    
        // Do any  additional setup after loading the view, typically from a nib.
    }
  
    /**
     This is an extremely complicated method that concatenates the first and last name and produces the full name.
     
     - Parameter firstname: The first part of the full name.
     - Parameter lastname: The last part of the fullname.
     - Returns: The full name as a string value.
     */
    
    func createFullName (_ firstname: String, lastname: String) -> String {
    return "\(firstname)\(lastname)"
       }
    ///Swift 中有两个基础的区间（Range）类型：Range 和 ClosedRange，并且这两个类型不能互相转换。这使得编写一个同时适用于两种区间类型的函数变得很困难。
    /// 你写了一个名为 random 的函数，它接受一个整数的区间，并返回一个该范围中的随机值：
    func random(from rang:Range<Int>) -> Int {
        let distance = rang.upperBound - rang.lowerBound
        let rand = arc4random_uniform(UInt32(distance))
        return rang.lowerBound + Int(rand)

    }
   // 由于这个特定的例子只涉及整数区间，因此我们还有另一个方案。基于整数的区间都是可以计数的，可计数的区间对应的半开区间 CountableRange 和闭合区间 CountableClosedRange 可以互相转换。所以我们可以把参数改为 CountableRange：

    
    func random(from rang: CountableRange<Int>) ->Int {

        let distance = rang.upperBound - rang.lowerBound
        let rand = arc4random_uniform(UInt32(distance))
        return rang.lowerBound + Int(rand)
    }
    
    
    
    
    
///    StackView
    
    
    @IBAction func setup(_ sender: Any) {
        
        UIView.animate(withDuration: 0.3, animations: {
            self.selectBtn.forEach {
            $0.isHidden = !$0.isHidden
            }
        })
    }
    
  
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

class FoodImageView: UIImageView, Shakeable {
    // 其他自定义写在这儿
    
}

class ActionButton: UIButton, Shakeable {
    // 其他自定义写在这儿
    override init(frame:CGRect) {
      super.init(frame: frame)
        self.backgroundColor = UIColor.red
        
        
        
    }
    
    required  init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.backgroundColor = UIColor.orange
        self.setTitle("点我颤抖", for: .normal)
//        fatalError("init(coder:) has not been implemented")
    }
}



///Swift 扩展「可以」添加存储属性


class Miller { }

class Cat {
    var name = "Puss"
    
}

private var catkey :UInt8 = 0

extension Miller {
    
    var cat: Cat {
        
        get{
            
            return associatedObject(self, key: &catkey)
            { return Cat() } // 设置变量的初始值
        }
        
        set {
           associateObject(self, key: &catkey, value: newValue)
            
        }
    }
}


public func with<T>(item: T, update: (inout T) throws -> Void) rethrows -> T {
    var this = item; try update(&this); return this
}



/**
let name = "News"
let storyboard = UIStoryboard(name: name, bundle: nil)
let identifier = "ArticleViewController"
let viewController = storyboard.instantiateViewControllerWithIdentifier(identifier) as! ArticleViewController

*/
///如何才能让 UIStoryboard 更安全






